<template>
	<view class="form">
		<u-form :model="form" :rules="rules" labelWidth="90" ref="oilForm">
			<!-- <u-form-item label="车牌号 :" prop="carNumber" @click="plateShow = true">
				<u-input v-model="form.carNumber" :disabled="true" disabledColor="#ffffff" border="bottom" placeholder="点击输入" />
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item> -->
			<u-form-item label="车牌号 :" prop="carNumber" @click="carNumberListShow()">
				<u-input v-model="form.carNumber" :disabled="true" disabledColor="#ffffff" border="bottom" placeholder="点击选择" />
				<u-icon slot="right" name="arrow-right"></u-icon>
			</u-form-item>
			<u-form-item label="当前里程 :" prop="travelMile">
				<u-input v-model="form.travelMile" border="bottom" placeholder="请输入当前里程" />
				<u-text slot="right" type="info" text="公里"></u-text>
			</u-form-item>
			<u-form-item label="加油金额 :" prop="amount">
				<u-input v-model="form.amount" border="bottom" placeholder="请输入加油金额" />
				<u-text slot="right" type="info" text="元"></u-text>
			</u-form-item>
			<u-form-item label="详细地址 :" prop="address" @click="selectLocation()">
				<u-input v-model="form.address" :disabled="true" disabledColor="#ffffff" border="bottom" placeholder="点击选择" />
				<u-icon slot="right" name="map" color="#5555ff"></u-icon>
			</u-form-item>
			<u-form-item label="加油站 :" prop="stationName">
				<u-input v-model="form.stationName" border="bottom" placeholder="例: 中国石油xx加油站" />
			</u-form-item>
			<u-form-item label="现场图片 :" prop="siteImage">
				<u-upload :fileList="fileList1" 
						@afterRead="afterRead" 
						@delete="deletePic" 
						name="1" 
						:maxCount="1"
						:multiple="true"
						v-model="form.siteImage">
				</u-upload>
			</u-form-item>
			<u-form-item label="收据图片 :" prop="receiptImage">
				<u-upload :fileList="fileList2" 
						@afterRead="afterRead" 
						@delete="deletePic" 
						name="2"
						:maxCount="1"
						:multiple="true"
						v-model="form.receiptImage">
				</u-upload>
			</u-form-item>
			<!-- <u-divider text="以下内容上传收据照片后自动带出"></u-divider> -->
			<u--text type="warning" text="注: 收据图片上传后自动识别出收据卡号、实收金额、卡片余额, 为了能够正确识别,请上传竖拍照片并保证照片足够清晰" size="10"></u--text>
			<u-form-item label="收据卡号 :" prop="cardNumber" style="margin-left: 20px;">
				<u-input v-model="form.cardNumber" border="bottom" placeholder="请输入收据卡号" />
			</u-form-item>
			<u-form-item label="实收金额 :" prop="receivedAmount">
				<u-input v-model="form.receivedAmount" border="bottom" placeholder="请输入实收金额" />
				<u-text slot="right" type="info" text="元"></u-text>
			</u-form-item>
			<u-form-item label="卡片余额 :" prop="cardBalance">
				<u-input v-model="form.cardBalance" border="bottom" placeholder="请输入卡片余额" />
				<u-text slot="right" type="info" text="元"></u-text>
			</u-form-item>
		</u-form>
		<u-button type="primary" 
				:hairline="false" 
				:disabled="submitLoading"
				:loading="submitLoading"
				customStyle="margin-top: 30px"
				text="提交"
				@click="submit">
		</u-button>
		<u-button type="error" 
				:hairline="true" 
				:disabled="resetLoading" 
				:loading="resetLoading"
				customStyle="margin-top: 10px"
				text="重置"
				@click="reset">
		</u-button>
		<!-- 车牌号选择 -->
		<u-picker :show="carNumberShow" 
			:columns="carNumberColumns" 
			:loading="carNumberLoading"
			closeOnClickOverlay=true
			@cancel="carNumberShow = false"
			@close="carNumberShow = false"
			@confirm="carNumberConfirm()"></u-picker>
		<!-- <plate-input v-if="plateShow" :plate="form.carNumber" @export="setPlate" @close="plateShow = false"/> -->
	</view>
</template>

<script>
	import config from "@/common/config.js"
	// import plateInput from '@/components/uni-plate-input/uni-plate-input.vue';
	export default {
		// components: {
		// 	plateInput
		// },
		data() {
			return {
				fileList1: [],
				fileList2: [],
				submitLoading: false,
				resetLoading: false,
				carNumberLoading: false,
				carNumberShow: false,
				carNumberColumns: [],
				// plateShow: false,
				form: {
					carNumber: '',
					travelMile: '',
					amount: '',
					stationName: '',
					address: '',
					longitude: '',
					latitude: '',
					siteImage: '',
					receiptImage: '',
					cardNumber: '',
					receivedAmount: '',
					cardBalance: ''
				},
				rules: {
					'carNumber': {
						type: 'string',
						required: true,
						message: '车牌号不能为空',
					},
					'travelMile': {
						type: 'number',
						required: true,
						message: '当前里程不能为空且必须为数字',
						trigger: ['change', 'blur']
					},
					'amount': {
						type: 'number',
						required: true,
						message: '加油金额不能为空且必须为数字',
						trigger: ['change', 'blur']
					},
					'stationName': {
						type: 'string',
						required: true,
						message: '加油站名称不能为空'
					},
					'address': {
						type: 'string',
						required: true,
						message: '详细地址不能为空'
					},
					'longitude': {
						type: 'number',
						required: true,
						message: '经度不能为空'
					},
					'latitude': {
						type: 'number',
						required: true,
						message: '纬度不能为空'
					},
					'siteImage': {
						type: 'string',
						required: true,
						message: '请上传现场图片'
					}, 
					'receiptImage': {
						type: 'string',
						required: true,
						message: '请上传收据图片'
					},
					'cardNumber': {
						type: 'string',
						required: true,
						message: '收据卡号不能为空'
					},
					'receivedAmount': {
						type: 'number',
						required: true,
						message: '收据实收金额不能为空'
					},
					'cardBalance': {
						type: 'number',
						required: true,
						message: '收据卡片余额不能为空'
					}
				},
				userInFo: {},
			}
		},
		onLoad() {
			// this.getUserinfo();
		},
		onReady() {
			this.$refs.oilForm.setRules(this.rules);
		},
		methods: {
			// setPlate(plate) {
			// 	if (plate.length >= 7) this.form.carNumber = plate;
			// 	this.plateShow = false;
			// },
			carNumberListShow(){
				let _that = this
				_that.carNumberLoading = true
				_that.carNumberShow = true
				let params = {}
				_that.$u.api.car.carNumberList(params).then((res) => {
					if(res.code === 0){
						_that.carNumberColumns = [[...res.data]]
					}
				});
				_that.carNumberLoading = false
			},
			carNumberConfirm(e) {
				this.carNumberShow = false;
				this.form.carNumber = e.value[0]
			},
			selectLocation() {
				let _that = this
				uni.getSetting({
					success(res) {
						if(res.authSetting['scope.userLocation'] === true){
							uni.chooseLocation({
								success: function(res) {
									_that.form.longitude = res.longitude;
									_that.form.latitude = res.latitude;
									_that.form.stationName = res.name;
									_that.form.address = res.address
								}
							});
						}else{
							uni.showModal({
								title: '即将跳转授权页面',
								content: '您没有授权获取您的位置',
								success(res){
									if(res.confirm){
										uni.openSetting()
									}
								}
							})
						}
					}
				})
			},
			// 删除图片
			deletePic(event) {
				console.log('event', event)
				this[`fileList${event.name}`].splice(event.index, 1)
				if (event.name == 1) {
					this.form.siteImage = ''
				} 
				if(event.name == 2){
					this.form.receiptImage = ''
					this.form.cardNumber = ''
					this.form.receivedAmount = ''
					this.form.cardBalance = ''
				}
			},
			// 新增图片
			async afterRead(event) {
				let _that = this
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = _that[`fileList${event.name}`].length
				lists.map((item) => {
					_that[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await _that.uploadFilePromise(lists[i].url)
					let item = _that[`fileList${event.name}`][fileListLen]
					_that[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.url
					}))
					fileListLen++
				}
				// 现场照片上传
				if(event.name == 1){
					_that.form.siteImage = _that.fileList1[0].url
				}
				// 收据照片上传，调用OCR识别
				if(event.name == 2){
					_that.form.receiptImage = _that.fileList2[0].url
					let params = {
						url: _that.fileList2[0].url
					}
					this.$u.api.ocr.recognize(params).then((res) => {
						if(res.code === 0){
							_that.form.cardNumber = res.data.cardNumber
							_that.form.receivedAmount = res.data.receivedAmount
							_that.form.cardBalance = res.data.cardBalance
						}
					})
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: config.baseUrl + '/smart/mini/file/upload',
						filePath: url,
						name: 'file',
						success: (res) => {
							let data = JSON.parse(res.data)
							setTimeout(() => {
								resolve(data.data)
							}, 1000)
						}
					});
				})
			},
			submit() {
				let _that = this
				this.submitLoading = true
				this.$refs.oilForm.validate().then(res => {
					_that.recordUpload()
				}).catch(errors => {
					_that.submitLoading = false
				})
			},
			recordUpload() {
				let _that = this
				let params = {
					...this.form
				}
				this.$u.api.record.recordAdd(params).then((res) => {
					if (res.code === 0) {
						uni.showToast({
							title: '上传成功',
							duration: 2000,
						});
						setTimeout(function() {
							_that.submitLoading = false
							uni.navigateBack();
						}, 700)
					} else {
						uni.showToast({
							title: e.msg,
							duration: 2000
						});
						setTimeout(function() {
							_that.submitLoading = false
						}, 700)
					}
				}).catch(err => {
						uni.showToast({
							title: '网络错误，请联系管理员',
							duration: 2000
						});
						setTimeout(function() {
							_that.submitLoading = false
						}, 700)
				});
			},
			reset(){
				this.resetLoading = true
				this.fileList1 = []
				this.fileList2 = []
				this.form.carNumber = ''
				this.form.travelMile = ''
				this.form.amount = ''
				this.form.stationName = ''
				this.form.address = ''
				this.form.longitude = 0
				this.form.latitude = 0
				this.form.siteImage = ''
				this.form.receiptImage = ''
				this.form.cardNumber = ''
				this.form.receivedAmount = ''
				this.form.cardBalance = ''
				this.$refs.oilForm.clearValidate()
				this.resetLoading = false
			}

			// getUserinfo() {
			// 	this.$u.api.userinfo({}).then((res) => {
			// 		this.userInFo = res.data
			// 	});
			// },
		},
	}
</script>

<style lang="scss" scoped>
	
	.form {
		margin-top: 50rpx;
		margin-left: 20rpx;
		margin-right: 20rpx;
		padding: 0 10rpx 100rpx 10rpx;
	}

</style>
